package com.woniuedu.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuedu.article.dto.AddDto;
import com.woniuedu.article.dto.ArticleDto;
import com.woniuedu.article.dto.LableDto;
import com.woniuedu.article.dto.LikeDto;
import com.woniuedu.article.entity.EduArticle;
import com.woniuedu.article.entity.EduArticleClass;
import com.woniuedu.article.entity.EduArticleComment;
import com.woniuedu.article.entity.EduArticleLable;
import com.woniuedu.article.mapper.EduArticleClassMapper;
import com.woniuedu.article.mapper.EduArticleCommentMapper;
import com.woniuedu.article.mapper.EduArticleLableMapper;
import com.woniuedu.article.mapper.EduArticleMapper;
import com.woniuedu.article.service.ArticleService;
import com.woniuedu.commonutils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author: Why
 * @Date: 2022/4/20 10:32
 * @Description: TODO
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<EduArticleMapper, EduArticle> implements ArticleService {

    @Autowired(required = false)
    EduArticleMapper eduArticleMapper;

    @Autowired(required = false)
    EduArticleClassMapper eduArticleClassMapper;

    @Autowired(required = false)
    EduArticleLableMapper eduArticleLableMapper;

    @Autowired(required = false)
    EduArticleCommentMapper eduArticleCommentMapper;

    private volatile static Map<String ,Boolean> saoMap = new ConcurrentHashMap<>();

    @Transactional
    @Override
    public R addArticle(AddDto addDto) {
        // 逻辑操作

        // 循环插入再将其放入DTO的id合集中
        for (String className : addDto.getNewClass()){
            EduArticleClass eduArticleClass = new EduArticleClass();
            eduArticleClass.setName(className);
            if (eduArticleClassMapper.insert(eduArticleClass) > 0){
                 addDto.getClassIds().add(eduArticleClass.getId());
            }
        }
        StringBuilder classIds = new StringBuilder();
        // 处理成数组
        for (Long ids : addDto.getClassIds()) {
            classIds.append(ids);
            classIds.append(",");
        }
        classIds.deleteCharAt(classIds.length() - 1);

        // 循环插入再将其放入DTO的id合集中
        for (String lableName : addDto.getNewLables()){
            EduArticleLable eduArticleLable = new EduArticleLable();
            eduArticleLable.setName(lableName);
            if (eduArticleLableMapper.insert(eduArticleLable) > 0){
                addDto.getLableIds().add(eduArticleLable.getId());
            }
        }
        // 处理成数组
        StringBuilder lableIds = new StringBuilder();
        for (Long ids : addDto.getLableIds()) {
            lableIds.append(ids);
            lableIds.append(",");
        }
        lableIds.deleteCharAt(lableIds.length() - 1);

        System.out.println(addDto);

        // 插入新的
        EduArticle eduArticle = new EduArticle();
        eduArticle.setContext(addDto.getContext());
        eduArticle.setTitle(addDto.getTitle());
        eduArticle.setCover(addDto.getCover());
        eduArticle.setClassIds(classIds.toString());
        eduArticle.setLableIds(lableIds.toString());
        eduArticle.setEditorType(addDto.getEditorType());
        eduArticle.setReleaseForm(addDto.getReleaseForm());
        eduArticle.setType(addDto.getType());
        eduArticle.setCreationTime(addDto.getCreationTime());
        int result = eduArticleMapper.insert(eduArticle);
        if (result > 0) {
            // 成功
            return R.ok().code(200).message("添加成功");
        } else {
            // 失败
            return R.error().code(500).message("添加失败");
        }
    }

    @Override
    @Transactional
    public R findById(Long id) {
        // 调用mapper
        EduArticle eduArticle = eduArticleMapper.selectById(id);
        if (eduArticle == null) {
            return R.error().code(500).message("没有找到文章");
        }
        // 找到了将文章的分类给找出来
        List<Long> classIds = Arrays.asList(eduArticle.getClassIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        // 通过classIds查找所有分类
        List<EduArticleClass> eduArticleClasses = eduArticleClassMapper.selectBatchIds(classIds);

        // 查找标签
        List<Long> lableIds = Arrays.asList(eduArticle.getLableIds().split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<EduArticleLable> eduArticleLables = eduArticleLableMapper.selectBatchIds(lableIds);

        ArticleDto articleDto = new ArticleDto();
        articleDto.setId(eduArticle.getId());
        articleDto.setTitle(eduArticle.getTitle());
        articleDto.setContext(eduArticle.getContext());
        articleDto.setCover(eduArticle.getCover());
        articleDto.setEditorType(eduArticle.getEditorType());
        articleDto.setIsDelete(eduArticle.getIsDelete());
        articleDto.setReleaseForm(eduArticle.getReleaseForm());
        articleDto.setClassList(eduArticleClasses);
        articleDto.setLableList(eduArticleLables);
        articleDto.setType(eduArticle.getType());
        articleDto.setHitNums(eduArticle.getHitNums()+1);
        articleDto.setCreationTime(eduArticle.getCreationTime());
        articleDto.setSummary(eduArticle.getSummary());



        // 获取该文章的评论
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("article_id",articleDto.getId());
        List<EduArticleComment> eduArticleComments = eduArticleCommentMapper.selectList(new QueryWrapper<EduArticleComment>().eq("article_id", articleDto.getId()).orderByAsc("creation_time"));
        // 先获取主评论，后面在获取追评
        List<EduArticleComment> comments = new ArrayList<>();
        for (int i = 0; i < eduArticleComments.size(); i++) {
            if (eduArticleComments.get(i).getReplyCommentId().equals(0L)){
                // 说明是主评论
                EduArticleComment comment = new EduArticleComment();
                comment.setId(eduArticleComments.get(i).getId());
                comment.setContext(eduArticleComments.get(i).getContext());
                comment.setArticleId(eduArticleComments.get(i).getArticleId());
                comment.setReplyCommentId(eduArticleComments.get(i).getReplyCommentId());
                comment.setIsDelete(eduArticleComments.get(i).getIsDelete());
                comment.setCreationTime(eduArticleComments.get(i).getCreationTime());
                comment.setLikesNums(eduArticleComments.get(i).getLikesNums());
                comment.setMemberId(eduArticleComments.get(i).getMemberId());
                comment.setCommentId(eduArticleComments.get(i).getCommentId());
                comment.setNickName(eduArticleComments.get(i).getNickName());
                comment.setReplyCommentNickName(eduArticleComments.get(i).getReplyCommentNickName());

                comments.add(comment);
            }
        }

        for (EduArticleComment comment : comments) {
            eduArticleComments.remove(comment);
        }

        articleDto.setComments(comments);
        articleDto.setReplyComments(eduArticleComments);

        // 修改阅读量+1

        if (saoMap.get(articleDto.getId()+"") == null){
            // 没获取到
            saoMap.put(articleDto.getId()+"",true);
            eduArticleMapper.updateHitNums(articleDto);
            System.out.println("修改阅读量");

        } else {
            // 存好了之后
//            if (saoMap.get(articleDto.getId()+"").equals(true)){
//                saoMap.put(articleDto.getId()+"",false);
//            } else {
//                eduArticleMapper.updateHitNums(articleDto);
//                System.out.println("修改阅读量");
//
//                saoMap.put(articleDto.getId()+"",true);
//            }
            saoMap.remove(articleDto.getId()+"");
        }


        return R.ok().code(200).message("获取文章成功").data("article",articleDto);
    }

    @Override
    public R findAllClassAndLable() {
        List<EduArticleLable> eduArticleLables = eduArticleLableMapper.selectList(null);
        List<EduArticleClass> eduArticleClasses = eduArticleClassMapper.selectList(null);
        List<LableDto> lableDtoList = new ArrayList<>();
        for (EduArticleLable lable : eduArticleLables){
            lableDtoList.add(new LableDto(lable.getId(),lable.getName()));
        }
        Map<String ,Object> map = new HashMap<>();
        map.put("allLable",lableDtoList);
        map.put("allClass",eduArticleClasses);
        return R.ok().code(200).message("获取标签和分类成功").data(map);
    }

    @Override
    public R findArticle(int pageNums, int pageSize) {
        PageHelper.startPage(pageNums, pageSize);
        List<EduArticle> allArticle = eduArticleMapper.findAllArticle();
        PageInfo<EduArticle> of = PageInfo.of(allArticle);
        return R.ok().code(200).message("获取成功").data("EduArticlePage",of);
    }

    @Override
    @Transactional
    public R like(LikeDto likeDto) {
        // 先判断是否存在
        LikeDto likeIsExsit = eduArticleMapper.likeIsExsit(likeDto);
        if(likeIsExsit != null){
            // 已存在 返回数据
            return R.error().code(500).message("已经点过赞");
        }

        if (eduArticleMapper.likeComment(likeDto) > 0){
            // 插入
            EduArticle eduArticle = new EduArticle();
            if (eduArticleMapper.likeCommentById(likeDto.getHaveLikedCommentId()) > 0){
                return R.ok().code(200).message("点赞成功");
            }
        }
        return R.error().code(500).message("服务器出问题稍后再试");

    }

    @Override
    public R unlike(LikeDto likeDto) {
        int i = eduArticleMapper.unLikeComment(likeDto);
        if (i > 0){
            if (eduArticleMapper.unLikeCommentById(likeDto.getHaveLikedCommentId()) > 0){
                return R.ok().code(200).message("取消点赞成功");
            }
        }
        return R.error().code(500).message("取消点赞失败");
    }

    @Override
    public R addComment(EduArticleComment comment) {
        // 添加
        if (eduArticleCommentMapper.insert(comment) > 0){
            comment.setLikesNums(0);
            comment.setIsDelete(0);
            return R.ok().code(200).message("评论成功").data("comment", comment);
        }

        return R.error().code(500).message("评论失败");
    }


}
